package tbalert.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import tbalert.hibernate3.Updater;
import tbalert.security.BadCredentialsException;
import tbalert.security.DisabledException;
import tbalert.security.UsernameNotFoundException;
import tbalert.session.SessionProvider;
import tbalert.web.PwdEncoder;
import tbalert.web.SysConstants;
import tbalert.web.WebErrors;
import tbalert.web.entity.Dwdm;
import tbalert.web.manager.DwdmMng;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;

@Controller
public class LoginAct {
	public static final String MESSAGE = "message";

	@RequestMapping(value = "/login.do", method = RequestMethod.GET)
	public String input(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		Dwdm bean = (Dwdm) session.getAttribute(request, SysConstants.DWDM_KEY);
		if (bean != null) {
			// 已登录，且会话未过期
			return "redirect:index.do";
		}
		return "login";
	}

	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	public String submit(String dlmc, String dlmm, String captcha, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		WebErrors errors = new WebErrors(request);
		try {
			if (!imageCaptchaService.validateResponseForID(session.getSessionId(request, response),
					captcha)) {
				errors.addErrorCode("error.invalidCaptcha");
			}
		} catch (CaptchaServiceException e) {
			errors.addErrorCode("error.exceptionCaptcha");
		}
		if (!errors.hasErrors()) {
			try {
				Dwdm dwdm = dwdmMng.login(dlmc, dlmm, request, response, session);
				if (dwdm.getDisabled()) {
					// 如果已经禁用，则退出登录。
					session.logout(request, response);
					throw new DisabledException(dwdm.getDlmc() + " 被禁用");
				}
				return "redirect:index.do";
			} catch (UsernameNotFoundException e) {
				errors.addErrorString(e.getMessage());
			} catch (BadCredentialsException e) {
				errors.addErrorString(e.getMessage());
			} catch (DisabledException e) {
				errors.addErrorString(e.getMessage());
			}
		}
		errors.toModel(model);
		return "login";
	}

	@RequestMapping(value = "/logout.do")
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		session.logout(request, response);
		return "redirect:login.do";
	}

	@RequestMapping(value = "/modify.do")
	public String modify(ModelMap model, HttpServletRequest request) {
		return "/changePwd";
	}

	@RequestMapping(value = "/changePwd.do")
	public String saveModify(ModelMap model, HttpServletRequest request, Dwdm dwdm, String resetPwd) {
		WebErrors errors = new WebErrors(request);
		Dwdm bean = (Dwdm) session.getAttribute(request, SysConstants.DWDM_KEY);
		if (pwdEncoder.isPasswordValid(bean.getDlmm(), dwdm.getDlmm())) {
			errors.addErrorCode("error.invalidPassword");
			errors.showErrorPage(model);
		}
		if (!pwdEncoder.isPasswordValid(bean.getDlmm(), dwdm.getDlmm())) {
			errors.addError("原始密码错误！");
			return errors.showErrorPage(model);
		}
		dwdm.setDlmm(pwdEncoder.encodePassword(resetPwd));
		Updater<Dwdm> updater = new Updater<Dwdm>(dwdm);
		updater.exclude("role");
		updater.exclude("sjdwId");
		updater.exclude("dlmc");
		dwdmMng.update(updater);
		errors.addError("单位信息修改成功，请重新登录系统！");
		errors.toModel(model);
		return "redirect:/logout.do";
	}

	@Autowired(required = true)
	private DwdmMng dwdmMng;

	@Autowired(required = true)
	private SessionProvider session;

	@Autowired(required = true)
	private ImageCaptchaService imageCaptchaService;

	@Autowired(required = true)
	private PwdEncoder pwdEncoder;

}
